package thread;

import utils.PrintUtils;

public class ThreadLocalTest {

    //创建一个ThreadLocal并初始化
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    ThreadLocal<Integer> threadLocal2 = ThreadLocal.withInitial(() -> 0);

    public class MyThread extends Thread {
        @Override
        public void run() {
            //获取ThreadLocal的值,注意ThreadLocal会从每个线程的ThreadLocalMap中获取值,
            //所以获取的数据不是线程共享的,每个线程中都存在一个副本,当前线程只会操作当前线程的数据
            Integer i = threadLocal.get();
            i++;
            threadLocal.set(i);

            Integer i2 = threadLocal2.get();
            i2++;
            threadLocal2.set(i2);

            PrintUtils.println("线程ID_" + getId() + ":" + threadLocal.get());
            PrintUtils.println("线程ID_" + getId() + ":" + threadLocal2.get());
        }
    }

    public void running() {
        for (int i = 0; i < 5; i++) {
            new MyThread().start();
        }
    }

    public static void main(String[] args) {
        new ThreadLocalTest().running();
    }
}
